<?php
if (!defined('CMS'))die;
global$Eleanor,$mainpage,$title;

$Eleanor->module['config'] = include($Eleanor->module['path'] .'config.php');
Eleanor::$Template->queue[]=$Eleanor->module['config']['admintpl'];

$lang=Eleanor::$Language->Load($Eleanor->module['path'].'lang_admin-*.php',$GLOBALS['Eleanor']->module['config']['n']);
Eleanor::LoadOptions($Eleanor->module['config']['opts'],false);

$mainpage=false;

$R = Eleanor::$Db->Query('SELECT COUNT(`status`) FROM `'.$Eleanor->module['config']['t'].'` WHERE `status`=-1');
list($cnt)=$R->fetch_row();

$Eleanor->Categories=new Categories_manager;
$Eleanor->Categories->table=$Eleanor->module['config']['c'];
$Eleanor->Categories->deletecb='DelCategories';

$Eleanor->module['links'] = array(
	'list' => $Eleanor->Url->Prefix(),
	'add'=>$Eleanor->Url->Construct(array('do'=>'add')),
	'options'=>$Eleanor->Url->Construct(array('do'=>'options')),
	'categories'=>$Eleanor->Url->Construct(array('do'=>'categories')),
);

$Eleanor->post=false;
$Eleanor->ct=array(
				 'language'=>Eleanor::$vars['multilang'] ? array(
								'title'=>$lang['language'],
								'descr'=>'',
								'type'=>'select',
								'bypost'=>&$Eleanor->post,
								'options'=>array(
											  'callback'=>'GetLanguages',
											  'addon'=>array(
														  'tabindex'=>1
													  ),
										  ),
							) : null,
				 'name'=>array(
							'title'=>$lang['tname'],
							'descr'=>'',
							'type'=>'edit',
							'bypost'=>&$Eleanor->post,
							'options'=>array(
										  'htmlsafe'=>true,
										  'addon'=>array(
													  'tabindex'=>2
												  ),
									  ),
						),
			 );

if (isset($_GET['do']))
	switch ($_GET['do']) {
	case'add':
		if ($_SERVER['REQUEST_METHOD']=='POST' and Eleanor::$our_query)
			Save(0);
		else
			AddEdit(0);
		break;
	case'categories':
		$Eleanor->Url->SetPrefix(array('do'=>'categories'),true);
		$c=$Eleanor->Categories->Show();
		if($c) {
			$c=Eleanor::$Template->Categories($c);
			Start();
			echo$c;
		}
		break;
	case'options':
		$Eleanor->Url->SetPrefix(array('do'=>'options'),true);
		$c=$Eleanor->Settings->GetInterface('group',$Eleanor->module['config']['opts']);
		Start();
		echo$c;
	break;
	case'draft':
		$t=isset($_POST['_draft']) ? (string)$_POST['_draft'] : '';
		if (preg_match('#^([nt])(\d+)$#',$t,$m)>0) {
			unset($_POST['_draft'],$_POST['back']);
			Eleanor::$Db->Replace(P.'drafts',array('key'=>$Eleanor->module['config']['n'].'-'.Eleanor::$Login->GetUserValue('id').'-'.$t,'value'=>serialize($_POST)));
		}
		Eleanor::$content_type='text/plain';
		Start('');
		echo'ok';
	break;
	default:
		ShowCatalog();
	}
elseif(isset($_GET['edit'])) {
	$id=(int)$_GET['edit'];
	if ($_SERVER['REQUEST_METHOD']=='POST' and Eleanor::$our_query)
		Save($id);
	else
		AddEdit($id);
}
elseif(isset($_GET['delete'])) {
	$id=(int)$_GET['delete'];
	if (!Eleanor::$our_query)
		return GoAway();
	$R = Eleanor::$Db->Query('SELECT `id`,`title` FROM `'.$Eleanor->module['config']['t'].'` LEFT JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) WHERE `id`='.$id.' AND `language` IN (\'\',\''.Language::$main.'\') LIMIT 1');
	if (!$a = $R->fetch_assoc())
		return GoAway(true);
	if (isset($_POST['ok'])) {
		Files::Delete(Eleanor::$root . Eleanor::$uploads . DIRECTORY_SEPARATOR . $Eleanor->module['config']['n'] .DIRECTORY_SEPARATOR . $id);

		Eleanor::$Db->Delete(P.'comments','`module`='.$Eleanor->module['config']['id'].' AND `contid`='.$id);
		Eleanor::$Db->Delete($Eleanor->module['config']['t'],'`id`='.$id.' LIMIT 1');
		Eleanor::$Db->Delete($Eleanor->module['config']['tl'],'`id`='.$id);

		Eleanor::$Db->Delete(P.'drafts','`key`=\''.$Eleanor->module['config']['n'].'-'.Eleanor::$Login->GetUserValue('id').'-n'.$id.'\' LIMIT 1');
		Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
		return GoAway(empty($_POST['back']) ? true : $_POST['back']);
	}
	$title=Eleanor::$Language[$Eleanor->module['config']['n']]['del_confirm'];
	if (isset($_GET['noback']))
		$back='';
	else
		$back=isset($_POST['back']) ? (string)$_POST['back'] : getenv('HTTP_REFERER');
	$c=Eleanor::$Template->Cover(Eleanor::$Template->Confirm(sprintf(Eleanor::$Language[$Eleanor->module['config']['n']]['submit_del'],$a['title']),$back));
	Start();
	echo$c;
}
elseif(isset($_GET['swap'])) {
	$id=(int)$_GET['swap'];
	if (Eleanor::$our_query) {
		$R = Eleanor::$Db->Query('SELECT `pinned`,`enddate`,`status` FROM `'.$Eleanor->module['config']['t'].'` WHERE `id`='.$id.' LIMIT 1');
		if (list($pin,$ed,$st)=$R->fetch_row() and ((int)$ed==0 or strtotime($ed)>time())) {
			if ($st <= 0) {
				if ($pin)
					Eleanor::$Db->Update($Eleanor->module['config']['t'],array('!status'=>'IF(`date`>`pinned` AND `date`<=NOW(),1,2)'),'`id`='.$id.' LIMIT 1');
				else
					Eleanor::$Db->Update($Eleanor->module['config']['t'],array('status'=>1),'`id`='.$id.' LIMIT 1');
			} else {
				Eleanor::$Db->Update($Eleanor->module['config']['t'],array('status'=>0),'`id`='.$id.' LIMIT 1');
			}
		}
		$R = Eleanor::$Db->Query('UPDATE `'.$Eleanor->module['config']['t'].'` INNER JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) SET `lstatus`=`status` WHERE `id`='.$id);
		Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
	}
	$back=getenv('HTTP_REFERER');
	GoAway($back ? $back.'#it'.$id : true);
} else
	ShowCatalog();

function ShowCatalog() {
	global$Eleanor,$title,$mainpage;
	$mainpage=true;
	$title=Eleanor::$Language[$GLOBALS['Eleanor']->module['config']['n']]['list'];
	$page=isset($_GET['page']) ? (int)$_GET['page'] : 1;
	$qs=$items=array();
	$where='';
	if (isset($_REQUEST['fi']) and is_array($_REQUEST['fi'])) {
		if ($_SERVER['REQUEST_METHOD']=='POST')
			$page=1;
		$qs['']['fi']=array();
		if (isset($_REQUEST['fi']['title'],$_REQUEST['fi']['titlet']) and $_REQUEST['fi']['title']!='') {
			$t=Eleanor::$Db->Escape((string)$_REQUEST['fi']['title'],false);
			switch ($_REQUEST['fi']['titlet']) {
			case'b':
				$t=' LIKE \''.$t.'%\'';
				break;
			case'm':
				$t=' LIKE \'%'.$t.'%\'';
				break;
			case'e':
				$t=' LIKE \'%'.$t.'\'';
				break;
			default:
				$t='=\''.$t.'\'';
			}
			$qs['']['fi']['title']=$_REQUEST['fi']['title'];
			$qs['']['fi']['titlet']=$_REQUEST['fi']['titlet'];
			$where.=' AND `title`'.$t;
		}
		if (!empty($_REQUEST['fi']['category']))
			if ($_REQUEST['fi']['category']=='no') {
				$qs['']['fi']['category']='';
				$where.=' AND `cats`=\'\'';
			}
			else {
				$qs['']['fi']['category']=(int)$_REQUEST['fi']['category'];
				$where.=' AND `cats` LIKE \'%,'.$qs['']['fi']['category'].',%\'';
			}
		if (isset($_REQUEST['fi']['status']) and $_REQUEST['fi']['status']!='-') {
			$qs['']['fi']['status']=(int)$_REQUEST['fi']['status'];
			$where.=$qs['']['fi']['status']==1 ? ' AND `status`IN(1,2)' : ' AND `status`='.$qs['']['fi']['status'];
		}
	}

	if (Eleanor::$our_query and isset($_POST['op'],$_POST['mass']) and is_array($_POST['mass']))
		do {
			$in=Eleanor::$Db->In($_POST['mass']);
			switch ($_POST['op']) {
			case'd':
				Eleanor::$Db->Update($Eleanor->module['config']['t'],array('status'=>0),'`id`'.$in);
				Eleanor::$Db->Update($Eleanor->module['config']['tl'],array('lstatus'=>0),'`id`'.$in);
				break;
			case'a':
				Eleanor::$Db->Update($Eleanor->module['config']['t'],array('status'=>1),'`id`'.$in.' AND `pinned`=\'0000-00-00 00:00:00\'');
				Eleanor::$Db->Update($Eleanor->module['config']['t'],array('!status'=>'IF(`date`>`pinned` AND `date`<=NOW(),1,2)'),'`id`'.$in.' AND `pinned`!=\'0000-00-00 00:00:00\'');
				break;
			case'm':
				Eleanor::$Db->Update($Eleanor->module['config']['t'],array('status'=>-1),'`id`'.$in);
				Eleanor::$Db->Update($Eleanor->module['config']['tl'],array('lstatus'=>-1),'`id`'.$in);
				break;
			case'k':

				foreach($_POST['mass'] as $v)
				Files::Delete(Eleanor::$root.Eleanor::$uploads.DIRECTORY_SEPARATOR.$Eleanor->module['config']['n'].DIRECTORY_SEPARATOR.(int)$v);
				Eleanor::$Db->Delete(P.'comments','`module`='.$Eleanor->module['id'].' AND `contid`'.Eleanor::$Db->In($_POST['mass']));
				Eleanor::$Db->Delete($Eleanor->module['config']['t'],'`id`'.$in);
				Eleanor::$Db->Delete($Eleanor->module['config']['tl'],'`id`'.$in);
				Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
				break 2;
			}
			Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
		}while (false);

	$R = Eleanor::$Db->Query('SELECT COUNT(`id`) FROM `'.$Eleanor->module['config']['t'].'` INNER JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) WHERE `language` IN (\'\',\''.Language::$main.'\')'.$where);
	list($cnt) = $R->fetch_row();
	if ($page <= 0)
		$page = 1;
	if (isset($_GET['new-pp']) and 4<$pp=(int)$_GET['new-pp'])
		Eleanor::SetCookie('per-page',$pp);
	else
		$pp=abs((int)Eleanor::GetCookie('per-page'));
	if ($pp<5 or $pp>500)
		$pp=50;
	$offset=abs(($page-1)*$pp);
	if ($cnt and $offset>=$cnt)
		$offset=max(0,$cnt-$pp);
	$sort=isset($_GET['sort']) ? $_GET['sort'] : '';
	if (!in_array($sort,array('id','title','date','author','status')))
		$sort='';
	$so=$_SERVER['REQUEST_METHOD']!='POST' && $sort && isset($_GET['so']) ? $_GET['so'] : 'desc';
	if ($so!='asc')
		$so='desc';
	if ($sort and ($sort!='id' or $so!='asc'))
		$qs+=array('sort'=>$sort,'so'=>$so);
	else
		$sort='id';
	$qs+=array('sort'=>false,'so'=>false);

	if ($cnt>0) {
		$R = Eleanor::$Db->Query('SELECT `id`,`cats`,`date`,`enddate`,`pinned`,`date`>`pinned` `_pinned`,`author`,`author_id`,`status`,`title` FROM `'.$Eleanor->module['config']['t'].'` INNER JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) WHERE `language` IN (\'\',\''.Language::$main.'\')'.$where.' ORDER BY `'.$sort.'` '.$so.' LIMIT '.$offset.', '.$pp);
		while ($a=$R->fetch_assoc()) {
			$a['cats']=$a['cats'] ? array_unique(explode(',,',trim($a['cats'],','))) : array();
			$items[]=$a;
		}
	}
	$links=array(
		'sort_id'=>$Eleanor->Url->Construct(array_merge($qs,array('sort'=>'id','so'=>$qs['sort']=='id' && $qs['so']=='asc' ? 'desc' : 'asc'))),
		'sort_title'=>$Eleanor->Url->Construct(array_merge($qs,array('sort'=>'title','so'=>$qs['sort']=='title' && $qs['so']=='asc' ? 'desc' : 'asc'))),
		'sort_date'=>$Eleanor->Url->Construct(array_merge($qs,array('sort'=>'date','so'=>$qs['sort']=='date' && $qs['so']=='asc' ? 'desc' : 'asc'))),
		'sort_author'=>$Eleanor->Url->Construct(array_merge($qs,array('sort'=>'author','so'=>$qs['sort']=='author' && $qs['so']=='asc' ? 'desc' : 'asc'))),
		'form_items'=>$Eleanor->Url->Construct($qs+array('page'=>$page>1 ? $page : false)),
		'pp'=>function($n)use($qs){ return$GLOBALS['Eleanor']->Url->Construct($qs+array('new-pp'=>$n)); },
		'first_page'=>$Eleanor->Url->Construct($qs),
		'pages'=>function($n)use($qs){ return$GLOBALS['Eleanor']->Url->Construct($qs+array('page'=>$n)); },
	);
	$Eleanor->Categories->Init($Eleanor->module['config']['c']);
	$c=Eleanor::$Template->CatalogList($items,$cnt,$pp,$qs,$page, $links);
	Start();
	echo$c;
}

function AddEdit($id,$error='') {
	global$Eleanor,$title;
	$lang=Eleanor::$Language[$Eleanor->module['config']['n']];
	if ($id) {
		$title[]=$lang['editing'];
		$R = Eleanor::$Db->Query('SELECT *,`date`>`pinned` `_pin` FROM `'.$Eleanor->module['config']['t'].'` WHERE id='.$id.' LIMIT 1');
		if (!$values = $R->fetch_assoc())
			return GoAway(true);

		if (!$error) {
			$values['_ping']=$values['status']!=1;
			$values['cats']=$values['cats'] ? explode(',,',trim($values['cats'],',')) : array();

#Служебное
			$values['_maincat']=reset($values['cats']);
			if ($values['status']==2)
				$values['status']=1;
			if ($values['_pin'] and (int)$values['pinned'])
				list($values['pinned'],$values['date'])=array($values['date'],$values['pinned']);

			$R = Eleanor::$Db->Query('SELECT `language`,`uri`,`title`,`text`,`info`,`meta_title`,`meta_descr`, `advertisement` FROM `'.$Eleanor->module['config']['tl'].'` WHERE `id`='.$id);
			while ($temp = $R->fetch_assoc())
				if (!Eleanor::$vars['multilang'] and (!$temp['language'] or $temp['language']==Language::$main)) {
					foreach(array_slice($temp,1) as $tk=>$tv)
					$values[$tk]=$tv;
					if (!$temp['language'])
						break;
				}
			elseif(!$temp['language'] and Eleanor::$vars['multilang']) {
				foreach(array_slice($temp,1) as $tk=>$tv)
				$values[$tk][Language::$main]=$tv;
				break;
			}
			elseif(Eleanor::$vars['multilang'] and isset(Eleanor::$langs[$temp['language']]))
			foreach(array_slice($temp,1) as $tk=>$tv)
			$values[$tk][$temp['language']]=$tv;

			if (Eleanor::$vars['multilang']) {
				$values['_onelang']=!is_array($values['title']) || count($values['title'])==1 && isset($values['title'][LANGUAGE]);
				foreach(Eleanor::$langs as $k=>&$v)
				if (!isset($values['title'][$k]))
					$values['title'][$k]=$values['text'][$k]=$values['info'][$k]=$values['advertisement'][$k]=$values['uri'][$k]=$values['meta_title'][$k]=$values['meta_descr'][$k]='';
			}
		}
	} else {
		$dv=Eleanor::$vars['multilang'] ? array(''=>'') : '';
		$values=array(
					'cats'=>array(),
					'date'=>date('Y-m-d H:i:s'),
					'pinned'=>'',
					'enddate'=>'',
					'author'=>Eleanor::$Login->GetUserValue('name',false),
					'author_id'=>Eleanor::$Login->GetUserValue('id'),
					'reads'=>0,
					'status'=>1,
#Языковые
					'title'=>$dv,
					'text'=>$dv,
					'info'=>$dv,
					'advertisement'=>$dv,
					'uri'=>$dv,
					'meta_title'=>$dv,
					'meta_descr'=>$dv,
#Специальные
					'_onelang'=>true,
					'_maincat'=>0,
					'price' => 0,
				);
		$title[]=$lang['adding'];
	}

	$hasdraft=false;
	if (!$error and !isset($_GET['nodraft'])) {
		$R = Eleanor::$Db->Query('SELECT `value` FROM `'.P.'drafts` WHERE `key`=\''.$Eleanor->module['config']['n'].'-'.Eleanor::$Login->GetUserValue('id').'-n'.$id.'\' LIMIT 1');
		if ($draft=$R->fetch_row() and $draft[0]) {
			$hasdraft=true;
			$_POST+=(array)unserialize($draft[0]);
			$error=true;
		}
	}

	if ($error) {
		$bypost=true;
		if ($error===true)
			$error='';

		if (Eleanor::$vars['multilang']) {
			$values['meta_title']=isset($_POST['meta_title']) ? (array)$_POST['meta_title'] : array();
			$values['meta_descr']=isset($_POST['meta_descr']) ? (array)$_POST['meta_descr'] : array();
			$values['title']=isset($_POST['title']) ? (array)$_POST['title'] : array();
			$values['text']=isset($_POST['text']) ? (array)$_POST['text'] : array();
			$values['info']=isset($_POST['info']) ? (array)$_POST['info'] : array();
			$values['advertisement']=isset($_POST['advertisement']) ? (array)$_POST['advertisement'] : array();
			$values['uri']=isset($_POST['uri']) ? (array)$_POST['uri'] : array();
			$values['_onelang']=isset($_POST['_onelang']);
		} else {
			$values['meta_title']=isset($_POST['meta_title']) ? (string)$_POST['meta_title'] : '';
			$values['meta_descr']=isset($_POST['meta_descr']) ? (string)$_POST['meta_descr'] : '';
			$values['title']=isset($_POST['title']) ? (string)$_POST['title'] : '';
			$values['text']=isset($_POST['text']) ? (string)$_POST['text'] : '';
			$values['info']=isset($_POST['info']) ? (string)$_POST['info'] : '';
			$values['advertisement']=isset($_POST['advertisement']) ? (string)$_POST['advertisement'] : '';
			$values['uri']=isset($_POST['uri']) ? (string)$_POST['uri'] : '';
		}
		$values['_maincat']=isset($_POST['_maincat']) ? (int)$_POST['_maincat'] : 0;
		$values['cats']=isset($_POST['cats']) ? (array)$_POST['cats'] : array();
		$values['date']=isset($_POST['date']) ? (string)$_POST['date'] : date('Y-m-d H:i:s');
		$values['enddate']=isset($_POST['enddate']) ? (string)$_POST['enddate'] : '';
		$values['pinned']=isset($_POST['pinned']) ? (string)$_POST['pinned'] : '';
		$values['author']=isset($_POST['author']) ? (string)$_POST['author'] : '';
		$values['author_id']=isset($_POST['author_id']) ? (string)$_POST['author_id'] : '';
		$values['reads']=isset($_POST['reads']) ? (int)$_POST['reads'] : '';
		$values['status']=isset($_POST['status']) ? (int)$_POST['status'] : '';
		$values['show_detail']=isset($_POST['show_detail']);
		$values['_ping']=isset($_POST['_ping']) && $values['status']==1;
		$values['price']=isset($_POST['price']) ? (float)$_POST['price'] : null;
	} else
		$bypost=false;

	$Eleanor->Categories->Init($Eleanor->module['config']['c']);
	$c=Eleanor::$Template->AddEdit($id,$values,$error,$Eleanor->Uploader->Show($id ? $Eleanor->module['config']['n'].DIRECTORY_SEPARATOR.$id : false),$bypost,$hasdraft);
	Start();
	echo$c;
}

function Save($id) {
	global$Eleanor;
	$lang=Eleanor::$Language[$Eleanor->module['config']['n']];
#Перечень переменных, которые дублируются для языковой таблицы ниже
	$maincat=isset($_POST['_maincat']) ? (int)$_POST['_maincat'] : false;
	$cats=isset($_POST['cats']) ? array_unique((array)$_POST['cats']) : array();
	if ($cats and count($cats)>1) {
		sort($cats,SORT_NUMERIC);
		if ($maincat!=$cats[0])
			array_unshift($cats,$maincat ? $maincat : reset($cats));
	}
	$cats=$cats ? ','.join(',,',$cats).',' : '';

	if (Eleanor::$vars['multilang'] and !isset($_POST['_onelang'])) {
		$langs=empty($_POST['lang']) || !is_array($_POST['lang']) ? array() : $_POST['lang'];
		$langs=array_intersect(array_keys(Eleanor::$langs),$langs);
		if (!$langs)
			$langs=array(Language::$main);
	}
	else
		$langs=array('');

	$values=array(
				'cats'=>$cats,
				'date'=>isset($_POST['date']) ? (string)$_POST['date'] : date('Y-m-d H:i:s'),
				'enddate'=>isset($_POST['enddate']) ? (string)$_POST['enddate'] : '',
				'pinned'=>isset($_POST['pinned']) ? (string)$_POST['pinned'] : '0000-00-00 00:00:00',
				'author'=>isset($_POST['author']) ? (string)$_POST['author'] : '',
				'author_id'=>isset($_POST['author_id']) ? (string)$_POST['author_id'] : 0,
				'reads'=>isset($_POST['reads']) ? (int)$_POST['reads'] : 0,
				'status'=>isset($_POST['status']) ? (int)$_POST['status'] : 1,
				'price'=>isset($_POST['price']) ? (float)$_POST['price'] : null,
			);
	if ($da=strtotime($values['date']) and $da>time())
		$values['status']=2;

	if ($values['enddate']) {
		$values['enddate']=strtotime($values['enddate']);
		if (!$values['enddate'])
			return AddEdit($id,$lang['err_enddate']);
		if ($values['status'] and $values['enddate']<=time())
			return AddEdit($id,$lang['err_enddate2']);
		$values['enddate']=date('Y-m-d H:i:s',$values['enddate']);
	}

	if ($values['author'] and $values['author_id']>0) {
		$R = Eleanor::$Db->Query('SELECT `id` FROM `'.USERS_TABLE.'` WHERE `name`=\''.Eleanor::$Db->Escape($values['author'],false).'\' LIMIT 1');
		if ($R->num_rows > 0)
			list($values['author_id'])=$R->fetch_row();
		else
			$values['author_id']=0;
	}
	$values['author']=htmlspecialchars($values['author'],ELENT,CHARSET,false);

	if ($da and $values['pinned'] and $pin=strtotime($values['pinned'])) {
		if ($pin<$da)
			return AddEdit($id,Eleanor::$Language[$Eleanor->module['config']['n']]['error_pinned']);
		elseif($values['status']>=1)
		list($values['date'],$values['pinned'])=array($values['pinned'],$values['date']);
	}
	else
		$values['pinned']='0000-00-00 00:00:00';

	if (Eleanor::$vars['multilang']) {
		$lvalues=array(
					 'title'=>array(),
					 'text'=>array(),
					 'info'=>array(),
					 'advertisement'=>array(),
					 'uri'=>array(),
					 'meta_title'=>array(),
					 'meta_descr'=>array(),
				 );
		foreach($langs as $l) {
			$lng=$l ? $l : Language::$main;
			$GLOBALS['Eleanor']->Editor->imgalt=$lvalues['title'][$lng]=(isset($_POST['title'],$_POST['title'][$lng]) and is_array($_POST['title'])) ? (string)Eleanor::$POST['title'][$lng] : '';
			$lvalues['text'][$lng]=isset($_POST['text'],$_POST['text'][$lng]) && is_array($_POST['text']) ? $Eleanor->Editor_Result->GetHtml((string)$_POST['text'][$lng], true) : '';
			$lvalues['info'][$lng]=isset($_POST['info'],$_POST['info'][$lng]) && is_array($_POST['info']) ? $Eleanor->Editor_Result->GetHtml((string)$_POST['info'][$lng],true) : '';
			$lvalues['advertisement'][$lng]=isset($_POST['advertisement'],$_POST['advertisement'][$lng]) && is_array($_POST['advertisement']) ? $Eleanor->Editor_Result->GetHtml((string)$_POST['advertisement'][$lng],true) : '';
			$lvalues['uri'][$lng]=isset($_POST['uri'],$_POST['uri'][$lng]) && is_array($_POST['uri']) ? (string)$_POST['uri'][$lng] : '';
			$lvalues['meta_title'][$lng]=isset($_POST['meta_title'],$_POST['meta_title'][$lng]) && is_array($_POST['meta_title']) ? (string)Eleanor::$POST['meta_title'][$lng] : '';
			$lvalues['meta_descr'][$lng]=isset($_POST['meta_descr'],$_POST['meta_descr'][$lng]) && is_array($_POST['meta_descr']) ? (string)Eleanor::$POST['meta_descr'][$lng] : '';
		}
	} else {
		$GLOBALS['Eleanor']->Editor->imgalt=isset($_POST['title']) ? (string)Eleanor::$POST['title'] : '';
		$lvalues=array(
					 'title'=>array(''=>$GLOBALS['Eleanor']->Editor->imgalt),
					 'text'=>array(''=>$Eleanor->Editor_Result->GetHtml('text')),
					 'info'=>array(''=>$Eleanor->Editor_Result->GetHtml('info')),
					 'advertisement'=>array(''=>$Eleanor->Editor->GetHtml('advertisement')),
					 'uri'=>array(''=>isset($_POST['uri']) ? (string)$_POST['uri'] : ''),
					 'meta_title'=>array(''=>isset($_POST['meta_title']) ? (string)Eleanor::$POST['meta_title'] : ''),
					 'meta_descr'=>array(''=>isset($_POST['meta_descr']) ? (string)Eleanor::$POST['meta_descr'] : ''),
				 );
	}

	$ml=in_array('',$langs) ? Language::$main : '';
	foreach(array('title','text', 'info', 'advertisement') as $field)
	foreach($lvalues[$field] as $k=>&$v)
	if (!$v and (in_array($k,$langs) or $ml==$k))
		return AddEdit($id,Eleanor::$Language[$Eleanor->module['config']['n']]['empty_'.$field]);

	foreach($lvalues['uri'] as $k=>&$v) {
		if ($v=='')
			$v=htmlspecialchars_decode($lvalues['title'][$k],ELENT);
		$v=$Eleanor->Url->Filter($v,$k);
		$R = Eleanor::$Db->Query('SELECT `id` FROM `'.$Eleanor->module['config']['t'].'` INNER JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) WHERE `uri`="'. $v .'" AND `language`'.($k ? 'IN(\'\',\''.$k.'\')' : '=\'\'').($id ? ' AND `id`!='.$id : null).' LIMIT 1');
		if ($R->num_rows > 0)
			$v='';
	}

	$date=$values['date'];
	$status=$values['status'];
	$ping=false;
	Eleanor::$Db->Delete(P.'drafts','`key`=\''.$Eleanor->module['config']['n'].'-'.Eleanor::$Login->GetUserValue('id').'-n'.$id.'\' LIMIT 1');
	if ($id) {
		if ($status==1) {
			$ping=isset($_POST['_ping']);
		}

		Eleanor::$Db->Update($Eleanor->module['config']['t'],$values,'id='.$id.' LIMIT 1');
		Eleanor::$Db->Delete($Eleanor->module['config']['tl'],'`id`='.$id.' AND `language`'.Eleanor::$Db->In($langs,true));
		foreach($langs as &$v) {
			if (Eleanor::$vars['multilang']) {
				$lang=$v ? $v : Language::$main;
				$values=array(
							'id'=>$id,
							'language'=>$v,
							'uri'=>$lvalues['uri'][$lang],
							'title'=>$lvalues['title'][$lang],
							'text'=>$lvalues['text'][$lang],
							'info'=>$lvalues['info'][$lang],
							'advertisement'=>$lvalues['advertisement'][$lang],
							'meta_title'=>$lvalues['meta_title'][$lang],
							'meta_descr'=>$lvalues['meta_descr'][$lang],
							'last_mod'=>date('Y-m-d H:i:s'),
						);
			} else
				$values=array(
							'id'=>$id,
							'language'=>'',
							'uri'=>$lvalues['uri'][''],
							'title'=>$lvalues['title'][''],
							'text'=>$lvalues['text'][''],
							'info'=>$lvalues['info'][''],
							'advertisement'=>$lvalues['advertisement'][''],
							'meta_title'=>$lvalues['meta_title'][''],
							'meta_descr'=>$lvalues['meta_descr'][''],
							'last_mod'=>date('Y-m-d H:i:s'),
						);
			$values['lstatus']=$status;
			$values['ldate']=$date;
			$values['lcats']=$cats;
			Eleanor::$Db->Replace($Eleanor->module['config']['tl'],$values);
		}
	} else {
		if ($status==1) {
			$ping=true;
		}
		Eleanor::$Db->Transaction();#Все ради аплоадера
		$id=Eleanor::$Db->Insert($Eleanor->module['config']['t'],$values);
		try {
			$ft=$Eleanor->Uploader->MoveFiles($Eleanor->module['config']['n'] . DIRECTORY_SEPARATOR . $id);
		}
		catch (EE$E) {
			Eleanor::$Db->Rollback();
			return AddEdit(false,$E->getMessage());
		}
		$values=array('id'=>array(),'language'=>array(),'uri'=>array(),'title'=>array(),'text'=>array(),
		'info'=>array(),
		'advertisement'=>array(),
		'meta_title'=>array(),'meta_descr'=>array());
		foreach($langs as &$v) {
			$values['id'][]=$id;
			$values['last_mod'][]=date('Y-m-d H:i:s');
			$values['lstatus'][]=$status;
			$values['ldate'][]=$date;
			$values['lcats'][]=$cats;
			if (Eleanor::$vars['multilang']) {
				$lang=$v ? $v : Language::$main;
				$values['language'][]=$v;
				$values['uri'][]=$lvalues['uri'][$lang];
				$values['title'][]=str_replace($ft['from'],$ft['to'],$lvalues['title'][$lang]);
				$values['text'][]=str_replace($ft['from'],$ft['to'],$lvalues['text'][$lang]);
				$values['info'][]=str_replace($ft['from'],$ft['to'],$lvalues['info'][$lang]);
				$values['advertisement'][]=str_replace($ft['from'],$ft['to'],$lvalues['advertisement'][$lang]);
				$values['meta_title'][]=$lvalues['meta_title'][$lang];
				$values['meta_descr'][]=$lvalues['meta_descr'][$lang];
			}
			else {
				$values['language'][]='';
				$values['uri'][]=$lvalues['uri'][''];
				$values['title'][]=str_replace($ft['from'],$ft['to'],$lvalues['title']['']);
				$values['text'][]=str_replace($ft['from'],$ft['to'],$lvalues['text']['']);
				$values['info'][]=str_replace($ft['from'],$ft['to'],$lvalues['info']['']);
				$values['advertisement'][]=str_replace($ft['from'],$ft['to'],$lvalues['advertisement']['']);
				$values['meta_title'][]=$lvalues['meta_title'][''];
				$values['meta_descr'][]=$lvalues['meta_descr'][''];
				break;
			}
		}
		Eleanor::$Db->Insert($Eleanor->module['config']['tl'], $values);
		Eleanor::$Db->Commit();
	}

	Eleanor::$Cache->Obsolete($Eleanor->module['config']['n'].'_nextrun');
	Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
	if ($ping and Eleanor::$vars['publ_ping']) {
		$Eleanor->Url->furl=Eleanor::$vars['furl'];
		$Eleanor->Url->file=Eleanor::$services['user']['file'];
		$sd=PROTOCOL.Eleanor::$domain.Eleanor::$site_path;
		Ping::Add(array('id'=>$Eleanor->module['config']['n'],'changes'=>$sd.$Eleanor->Url->Prefix(),'rss'=>$sd.Eleanor::$services['rss']['file'].'?'.Url::Query(Eleanor::$vars['multilang'] && Language::$main!=LANGUAGE ? array('lang'=>Eleanor::$langs[Language::$main]['uri'],'module'=>$Eleanor->module['name']) : array('module'=>$Eleanor->module['name']))));
	}

	###########
	$qr = $R = Eleanor::$Db->Query('SELECT `image` FROM `'. $Eleanor->module['config']['i'] .'` WHERE `catalog_id` = "'. $id .'"');
	$b = array();
	while($a = $qr->fetch_row()) {
		$b[] = $a[0];
	}

	$images_path = $Eleanor::$rootf . '/uploads/catalog/'. $id;
	if (is_dir($images_path)) {
		$data = array();
		foreach(scandir($images_path) as $v) {
			if ($v === '..' || $v === '.')
				continue;
			if (strpos($v, 'preview') !== false)
				$data[] = '/uploads/catalog/'. $id .'/'. $v;
		}
		$add = array_diff($data, $b);
		$delete = array_diff($b, $data);
		if ($delete) {
			Eleanor::$Db->Delete($Eleanor->module['config']['i'], '`catalog_id` = "'. $id .'" AND ( `image` = "'. implode('" OR `image` = "', $delete) .'" )');
		}

		if ($add) {
			foreach($add as &$img){
				$insert[] = array(
					'catalog_id' => $id,
					'image' => $img,
				);
			}
			Eleanor::$Db->Insert($Eleanor->module['config']['i'], $insert);
		}
	}
	GoAway(getenv('HTTP_REFERER'));
}

#Служебное
function GetLanguages($a) {
	global$Eleanor;
	$sel=Eleanor::Option(Eleanor::$Language[$Eleanor->module['config']['n']]['forallt'],'',in_array('',$a['value']));
	foreach(Eleanor::$langs as $k=>&$v)
	$sel.=Eleanor::Option($v['name'],$k,in_array($k,$a['value']));
	return$sel;
}

function DelCategories($ids) {
	global$Eleanor;
#К сожалению в MySQL не предусмотрена функция замены по регулярному выражению. Расставляем грабли.
	foreach($ids as &$v) {
		Eleanor::$Db->Update($Eleanor->module['config']['t'],array('!cats'=>'REPLACE(`cats`,\','.$v.',\',\'\')'));
		Eleanor::$Db->Update($Eleanor->module['config']['tl'],array('!lcats'=>'REPLACE(`lcats`,\','.$v.',\',\'\')'));
	}
	Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
}